import type { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';

// 分页元数据
export interface PaginationMeta {
    page: number;
    page_size: number;
    total: number;
    total_pages: number;
    has_more: boolean;
}

// 基础响应结构
interface BaseResponse {
    code: number;
    message: string;
}

// 空响应
export interface EmptyResponse extends BaseResponse {
    data: null;
    meta: null;
}

// 单个对象响应
export interface SingleResponse<T> extends BaseResponse {
    data: T;
    meta: null;
}

// 分页列表响应
export interface ListResponse<T> extends BaseResponse {
    data: T[];
    meta: PaginationMeta;
}

// 统一响应类型（空响应、单个对象或列表）
export type ResponseData<T> = EmptyResponse | SingleResponse<T> | ListResponse<T>;

// 原始响应数据，包含完整结构
export interface FullResponse<T> {
    data: ResponseData<T>;
    status: number;
    statusText: string;
    headers: Record<string, string>;
    config: AxiosRequestConfig;
}

// 自定义请求配置
export interface RequestOptions {
    // 是否显示加载中
    showLoading?: boolean;
    // 是否显示错误信息
    showError?: boolean;
    // 自定义错误处理
    onError?: (error: Error | AxiosError) => void;
}

// 请求配置
export interface CreateRequestConfig<T = unknown> extends AxiosRequestConfig {
    requestOptions?: RequestOptions;
    interceptors?: RequestInterceptors<T>;
}

// 拦截器
export interface RequestInterceptors<T = unknown> {
    // 请求拦截
    requestInterceptor?: (config: CreateRequestConfig<T>) => CreateRequestConfig<T>;
    requestInterceptorCatch?: (error: Error | AxiosError) => Promise<Error>;
    // 响应拦截
    responseInterceptor?: (response: AxiosResponse<ResponseData<T>>) => AxiosResponse<ResponseData<T>>;
    responseInterceptorCatch?: (error: Error | AxiosError) => Promise<Error>;
}

// 类型守卫
export const typeGuards = {
    // 判断响应是否为空
    isEmptyResponse: <T>(response: ResponseData<T>): response is EmptyResponse => {
        return response.data === null && response.meta === null;
    },

    // 判断响应是否为列表类型
    isListResponse: <T>(response: ResponseData<T>): response is ListResponse<T> => {
        return Array.isArray(response.data) && response.meta !== null;
    },

    // 判断响应是否为单个对象类型
    isSingleResponse: <T>(response: ResponseData<T>): response is SingleResponse<T> => {
        return response.data !== null && !Array.isArray(response.data) && response.meta === null;
    }
}; 